package com.erbao.dp.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Random;

class Tank {
    public void move() {
        System.out.println("tank moving calalalala……");
        // 模拟坦克移动时间
        try {
            Thread.sleep(new Random().nextInt(10000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class LogInterceptor implements MethodInterceptor{

    private void before(){
        System.out.println("tank start......");
    }

    private void after(){
        System.out.println("tank stopped......");
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println(o.getClass().getSuperclass().getName()); // o 是tank的子类，如果是final类无法使用cglib
        before();
        Object result = methodProxy.invokeSuper(o, null);
        after();
        return result;
    }
}

/**
 * @author CaoBaoYin
 * @since 21/9/17 17:19
 */
public class Main {

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Tank.class);
        enhancer.setCallback(new LogInterceptor());
        Tank tank = (Tank) enhancer.create();
        tank.move();
    }

}
